package org.happen.android.core.net;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.happen.android.bean.BaseRequest;
import org.happen.android.bean.entity.KeyValue;
import org.happen.android.bean.response.FailResponse;
import org.happen.android.bean.response.JsonStrResponse;
import org.happen.android.core.annotation.ReqParam;
import org.liushui.mycommons.android.log.McLog;
import org.liushui.mycommons.android.util.McToastUtil;

import android.text.TextUtils;

public class ReqRespUtils
{

	/**
	 * 生成Get请求的url
	 * 
	 * @ReqParam request
	 */
	public static String makeGetUrl(BaseRequest request)
	{
		List<KeyValue> params = request.getGetParams();
		if (params == null)
		{
			params = new ArrayList<KeyValue>();
		}

		Class<?> cls = request.getClass();
		Field[] fs = cls.getFields();

		for (Field f : fs)
		{
			int modi = f.getModifiers();
			if (Modifier.isStatic(modi))
			{
				continue;
			}
			ReqParam reqParam = f.getAnnotation(ReqParam.class);
			if (reqParam != null && !reqParam.asParam())
			{
				// 不作为参数传递
				continue;
			}
			KeyValue kv = new KeyValue();
			if (reqParam == null || TextUtils.isEmpty(reqParam.value()))
			{
				kv.key = f.getName();
			} else
			{
				kv.key = reqParam.value();
			}

			f.setAccessible(true);
			try
			{
				Object obj = f.get(request);
				if (obj == null)
				{
					if (reqParam != null)
					{
						if (reqParam.required())
						{
							McLog.e(f.getName() + " is null,but it is required.");
							kv.value = "";
							params.add(kv);
						} else
						{
							// 为空则不处理，不作为参数传递
							// kv.value = "";
						}
					} else
					{
						kv.value = null; // ?
						params.add(kv);
					}
				} else
				{
					kv.value = obj.toString();
					params.add(kv);
				}
			} catch (IllegalArgumentException e)
			{
				e.printStackTrace();
			} catch (IllegalAccessException e)
			{
				e.printStackTrace();
			}
		}
		StringBuffer normalSb = new StringBuffer();
		boolean isFirst = true;
		for (KeyValue kv : params)
		{
			if (isFirst)
			{
				isFirst = false;
			} else
			{
				normalSb.append("&");
			}

			String v2 = TextUtils.isEmpty(kv.value) ? "" : kv.value;
			normalSb.append(kv.key + "=" + encode(v2));
		}
		if (TextUtils.isEmpty(request.url))
		{
			McLog.w(request.getClass() + "'s url is empty, please check!!!");
		}
		String geturl2 = request.url + "?" + normalSb.toString();
		return geturl2;
	}

	static String encode(String s)
	{
		try
		{
			return URLEncoder.encode(s, "utf-8");
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return "";
	}

	public static void showResp(JsonStrResponse jsonResponse)
	{
		if (!TextUtils.isEmpty(jsonResponse.error))
		{
			McToastUtil.show(jsonResponse.error);
		}
	}

	public static boolean showRespException(Exception e)
	{
		if (FailResponse.NET_EX.exception.equals(e))
		{
			McToastUtil.show("网络较差，请稍后重试。");
			return true;
		} else if (FailResponse.JSON_EX.exception.equals(e))
		{
			//McToastUtil.show("Json转化出错，可能是服务器问题，稍后重试。");
			McToastUtil.show("服务器出错，稍后重试。");
			return true;
		} else if (FailResponse.TOKEN_EX.exception.equals(e))
		{
			McToastUtil.show("登录状态失效，请重新登录。");
			//登录状态失效，请重新登录
			return true;
		}
		McToastUtil.show(e.getMessage());
		return false;
	}
}